package org.kernely.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.kernely.core.service.KernelyBundleService;
import org.kernely.ui.services.KernelyUIBundle;
import org.kernely.ui.services.KernelyUIBundleService;
import org.kernely.ui.services.KernelyUIBundleServiceListener;

public class KernelyUIBundleServiceImpl implements KernelyUIBundleService {

	// List of all KernelyUIBundle deployed
	private ArrayList<KernelyUIBundle> uiBundles = new ArrayList<KernelyUIBundle>();

	// List of all KernelyUIBundleListener registered
	private ArrayList<KernelyUIBundleServiceListener> listeners = new ArrayList<KernelyUIBundleServiceListener>();

	/**
	 * @see KernelyUIBundleService.registerModule
	 */
	@SuppressWarnings("unchecked")
	public final synchronized void registerModule(KernelyUIBundle module) {
		uiBundles.add(module);
		// Fired the event that a new bundle has been deployed to all listeners
		for (KernelyUIBundleServiceListener listener : (ArrayList<KernelyUIBundleServiceListener>) listeners.clone()) {
			listener.moduleRegistered(this, module);
		}
	}

	/**
	 * @see KernelyUIBundleService.unregisterModule
	 */
	@SuppressWarnings("unchecked")
	public final synchronized void unregisterModule(KernelyUIBundle module) {
		uiBundles.remove(module);

		// Fired the event that a bundle has been undeployed to all listeners
		for (KernelyUIBundleServiceListener listener : (ArrayList<KernelyUIBundleServiceListener>) listeners.clone()) {
			listener.moduleUnregistered(this, module);
		}
	}

	/**
	 * @see KernelyBundleService.getModules
	 */
	public final List<KernelyUIBundle> getUIBundles() {
		return Collections.unmodifiableList(uiBundles);
	}

	/**
	 * @see KernelyBundleService.addListener
	 */
	@Override
	public final synchronized void addListener(KernelyUIBundleServiceListener listener) {
		listeners.add(listener);
	}

	/**
	 * @see KernelyBundleService.removeListener
	 */
	@Override
	public final synchronized void removeListener(KernelyUIBundleServiceListener listener) {
		listeners.remove(listener);
	}

}